from django.conf import settings
from django.shortcuts import render

from django.shortcuts import render
from django.views import View


# /test/
from django.views.generic import CreateView
from itsdangerous.jws import TimedJSONWebSignatureSerializer
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User
from users.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer


class TestView(View):

    def get(self,request):
        return render(request, 'test.html')


# /test2/
class TestView2(APIView):

    def get(self, request):
        # print('1'+1)
        response = Response({'message': 'get请求'})
        # 设置响应头参数，允许前端html8080访问调用当前接口(视图)服务器8000  键值对的方式
        # response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
        # print(response)
        return response

    # 判断用户名是否重名
class UsernameCountView(APIView):
   # 前端请求的接口路由  usernames / (?P < username >\w{5, 20}) / count /
    def get(self,request,username):
        # 这里得到的是一个查询集，查询username这个名字在里面有多少条  判断是否重名
        count = User.objects.filter(username=username).count()
        print(count)
        context = {
            'username':username,
            'count':count,
        }
        return Response(context)


class CreateUserView(CreateAPIView):
    """注册用户"""
    serializer_class =  CreateUserSerializer


# /user/
class UserDetailView(RetrieveAPIView):
    """查询一个用户的详情信息"""

    serializer_class = UserDetailSerializer
    queryset = User.objects.all()

    # 登录之后才能访问当前接口
    permission_classes = [IsAuthenticated]

    # 获取一个数据(登录的用户对象)
    def get_object(self):
        return self.request.user

class EmailView(UpdateAPIView):
    """修改用户数据(邮箱)"""

    queryset = User.objects.all()
    serializer_class = EmailSerializer

    # 登录后能才调用此接口
    permission_classes = [IsAuthenticated]

    # def put(self, request, *args, **kwargs):
    #     email = request.data.get('email')
    #     return super().put(request, *args, **kwargs)

    def get_object(self):
        # 表示要修改的是哪个用户对象
        return self.request.user

# /email/verification/
class VerifyEmailView(APIView):
    """激活用户邮箱"""

    def get(self, request):
        # 获取请求参数token
        token = request.query_params.get('token')
        # itsdangerous校验token的合法性
        try:
            s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,60*60*24)
            dict_data = s.loads(token) # 验证签名
        except:  # token被篡改了或失败   一定要指定状态码
            return Response({'message':'token无效'},status=400)
        # 从token中获取用户user_id,email
        user_id = dict_data.get('user_id')
        email = dict_data.get('email')

        # 数据库中查询出要激活的对象
        try:
            user= User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            return Response({'message':'用户不存在'},status=404)
        # 修改用户对象的激活字段为true：　ｅｍａil_active = True
        user.email_active = True
        user.save()
        # 响应数据
        return Response({'message':'OK'})









